<template>
  <div class="report-container" ref="exportArea">
    <!-- 页眉 -->
    <div class="report-header">
      <div class="logo-container">
        <img src="@/assets/logo/logo.png" alt="Logo" class="logo" />
      </div>
      <div class="title-container">
        <h1 class="main-title">心语云·学生心理健康状况测评报告(学生版)</h1>
        <p class="sub-title">青少年心理与行为研究中心</p>
      </div>
      <div class="action-buttons">
        <el-button type="primary" @click="downloadPdf">下载PDF</el-button>
        <el-button type="success" @click="downloadWord">导出Word</el-button>
        <el-button @click="$router.go(-1)">返回</el-button>
      </div>
    </div>

    <!-- 学生基本信息 -->
    <div class="info-section">
      <div class="section-title">学生基本信息</div>
      <div class="info-content">
        <div class="info-row">
          <div class="info-item">
            <label>姓名：</label>
            <span>{{ userInfo.name }}</span>
          </div>
          <div class="info-item">
            <label>性别：</label>
            <span>{{ userInfo.sex }}</span>
          </div>
          <div class="info-item">
            <label>年龄：</label>
            <span>{{ userInfo.age || "暂无数据" }}</span>
          </div>
        </div>
        <div class="info-row">
          <div class="info-item">
            <label>学校：</label>
            <span>{{ userInfo.school }}</span>
          </div>
          <div class="info-item">
            <label>测评时间：</label>
            <span>{{ userInfo.time }}</span>
          </div>
          <div class="info-item">
            <label>用时：</label>
            <span>{{ formatDuration(userInfo.duration) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 综合测评报告 -->
    <div class="result-section">
      <div class="section-title">综合测评报告</div>
      <div class="result-content">
        <div class="result-summary">
          <div class="result-label">测评结果：</div>
          <div class="result-value">{{ getComprehensiveResult() }}</div>
        </div>
        <div class="result-visual">
          <div class="indicator-container">
            <div
              class="indicator"
              :style="{ left: getIndicatorPosition() }"
            ></div>
          </div>
          <div class="scale">
            <div
              class="scale-item"
              v-for="(item, index) in comprehensiveScale"
              :key="index"
              :class="{ active: index === comprehensiveIndex }"
            >
              {{ item }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 积极指标 -->
    <div class="indicators-section">
      <div class="section-title">积极指标</div>
      <div class="indicators-table">
        <table>
          <thead>
            <tr>
              <th>积极指标</th>
              <th>很高</th>
              <th>较高</th>
              <th>较低</th>
              <th>很低</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in reportData.active" :key="item.id">
              <td>{{ item.assessTableName }}</td>
              <td>
                <i v-if="item.level === '很高'" class="el-icon-check"></i>
              </td>
              <td>
                <i v-if="item.level === '较高'" class="el-icon-check"></i>
              </td>
              <td>
                <i v-if="item.level === '较低'" class="el-icon-check"></i>
              </td>
              <td>
                <i v-if="item.level === '很低'" class="el-icon-check"></i>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 积极指标评估结果 -->
    <div class="indicators-section">
      <div class="section-title">积极指标评估结果</div>
      <div class="indicators-result">
        <div
          v-for="(item, index) in reportData.active"
          :key="index"
          class="indicator-result-item"
        >
          <div class="indicator-name">
            {{ item.assessTableName }}测评结果：
            <span
              :style="{
                color: getLevelColor(item.level, 'active'),
              }"
            >
              {{ item.level }}
            </span>
          </div>
          <div class="result-visual">
            <div class="indicator-container">
              <div
                class="indicator"
                :style="{ left: getActiveIndicatorPosition(item.level) }"
              ></div>
            </div>
            <div class="scale">
              <div
                class="scale-item"
                v-for="(level, levelIndex) in ['很低', '较低', '较高', '很高']"
                :key="levelIndex"
                :class="{ active: level === item.level }"
              >
                {{ level }}
              </div>
            </div>
          </div>
          <div class="indicator-description">
            {{ item.detail }}
          </div>
        </div>
      </div>
    </div>

    <!-- 消极指标 -->
    <div class="indicators-section">
      <div class="section-title">消极指标</div>
      <div class="indicators-table">
        <table>
          <thead>
            <tr>
              <th>消极指标</th>
              <th>正常</th>
              <th>轻度</th>
              <th>中度</th>
              <th>重度</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in reportData.negative" :key="item.id">
              <td>{{ item.assessTableName }}</td>
              <td>
                <i v-if="item.level === '正常'" class="el-icon-check"></i>
              </td>
              <td>
                <i v-if="item.level === '轻度'" class="el-icon-check"></i>
              </td>
              <td>
                <i v-if="item.level === '中度'" class="el-icon-check"></i>
              </td>
              <td>
                <i v-if="item.level === '重度'" class="el-icon-check"></i>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 消极指标评估结果 -->
    <div class="indicators-section">
      <div class="section-title">消极指标评估结果</div>
      <div class="indicators-result">
        <div
          v-for="(item, index) in reportData.negative"
          :key="index"
          class="indicator-result-item"
        >
          <div class="indicator-name">
            {{ item.assessTableName }}测评结果：
            <span
              :style="{
                color: getLevelColor(item.level, 'negative'),
              }"
            >
              {{ item.level }}
            </span>
          </div>
          <div class="result-visual">
            <div class="indicator-container">
              <div
                class="indicator"
                :style="{ left: getNegativeIndicatorPosition(item.level) }"
              ></div>
            </div>
            <div class="scale">
              <div
                class="scale-item"
                v-for="(level, levelIndex) in ['正常', '轻度', '中度', '重度']"
                :key="levelIndex"
                :class="{ active: level === item.level }"
              >
                {{ level }}
              </div>
            </div>
          </div>
          <div class="indicator-description">
            {{ item.detail }}
          </div>
        </div>
      </div>
    </div>

    <!-- 说明 -->
    <div class="explanation-section">
      <div class="section-title">说明</div>
      <div class="explanation-content">
        <p>通过测评得知该生：{{ getComprehensiveDescribeName() }}</p>
        <p>{{ getComprehensiveDescribe() }}</p>
      </div>
    </div>
    <!-- 干预措施建议 -->
    <div class="recommendation-section">
      <div class="section-title">干预措施建议</div>
      <div class="recommendation-content">
        <p>{{ getComprehensiveMeasure() }}</p>
      </div>
    </div>

    <!-- 页脚 -->
    <div class="report-footer">
      <div class="qrcode">
        <!-- 可以放置二维码 -->
      </div>
    </div>
  </div>
</template>

<script>
import { getReportDetailss } from "@/api/system/report";
import html2pdf from "html2pdf.js";

export default {
  name: "ReportDetail",
  props: {
    userId: {
      type: [String, Number],
      default: "",
    },
    taskId: {
      type: [String, Number],
      default: "",
    },
    standalone: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      comprehensiveScale: ["心理健康良好", "1级预警", "2级预警", "3级预警"],
      comprehensiveIndex: 0,
      loading: false,
      reportData: {
        userInfo: {
          name: "",
          sex: "",
          age: "",
          school: "",
          time: "",
          duration: 0,
        },
        active: [],
        negative: [],
        comprehensive: [],
      },
    };
  },
  computed: {
    userInfo() {
      const schoolInfo = this.reportData.userInfo?.school || "";
      const schoolParts = schoolInfo.split("-");
      const sex = this.reportData.userInfo?.sex;
      const sexText = sex;
      return {
        name: this.reportData.userInfo?.name || "",
        sex: sexText,
        age: this.reportData.userInfo?.age || "暂无数据",
        school: schoolParts[2] || "",
        time: this.reportData.userInfo?.time || "",
        duration: this.reportData.userInfo?.duration || 0,
      };
    },
  },
  created() {
    this.getReportData();
  },
  mounted() {
    // 如果URL中包含download=true参数，加载完成后自动下载PDF
    if (this.$route.query.download === "true") {
      // 等待页面渲染完成
      this.$nextTick(() => {
        // 延迟一秒执行下载，确保数据加载完成
        setTimeout(() => {
          this.downloadPdf();
        }, 1000);
      });
    }
  },
  methods: {
    getReportData() {
      this.loading = true;
      getReportDetailss({
        taskId: this.$route.query.taskId,
        userId: this.$route.query.userId,
      })
        .then((response) => {
          this.reportData = response.data;
          this.loading = false;
        })
        .catch((error) => {
          console.error("获取报告详情失败", error);
          this.$message.error("获取报告详情失败");
          this.loading = false;
        });
    },
    getIndicatorPosition() {
      const index = this.reportData.comprehensive.findIndex(
        (item) => item.check
      );
      return index === -1 ? "0%" : `${(index + 0.5) * 25}%`;
    },

    downloadPdf() {
      const options = {
        margin: 10,
        filename: `心理健康评估报告_${
          this.userInfo.name
        }_${new Date().getTime()}.pdf`,
        image: { type: "jpeg", quality: 0.98 },
        html2canvas: { scale: 2, useCORS: true },
        jsPDF: { unit: "mm", format: "a4", orientation: "portrait" },
      };

      const element = document.querySelector(".report-container");

      this.$message({
        message: "正在生成PDF，请稍候...",
        type: "info",
        duration: 0,
      });

      html2pdf()
        .from(element)
        .set(options)
        .save()
        .then(() => {
          this.$message.closeAll();
          this.$message({
            message: "PDF下载成功",
            type: "success",
            duration: 2000,
          });
        })
        .catch((error) => {
          console.error("PDF生成失败", error);
          this.$message.closeAll();
          this.$message.error("PDF生成失败，请重试");
        });
    },
    closeWindow() {
      window.close();
    },
    getComprehensiveResult() {
      const selectedResult = this.reportData.comprehensive?.find(
        (item) => item.check
      );
      return selectedResult ? selectedResult.name : "暂无数据";
    },
    getComprehensiveDescription() {
      // 获取积极指标
      const positiveIndicators = this.reportData.active
        .filter((item) => ["很高", "较高"].includes(item.level))
        .map((item) => `${item.assessTableName}水平${item.level}`);

      // 获取消极指标
      const negativeIndicators = this.reportData.negative
        .filter((item) => ["轻度", "中度", "重度"].includes(item.level))
        .map((item) => `${item.assessTableName}${item.level}`);

      // 构建描述
      let description =
        (positiveIndicators.length > 0
          ? positiveIndicators.join("，")
          : "无明显积极指标") +
        "。该生存在以下心理健康问题：" +
        (negativeIndicators.length > 0
          ? negativeIndicators.join("，")
          : "无明显心理健康问题") +
        "。";

      return description;
    },
    getComprehensiveMeasure() {
      const selectedResult = this.reportData.comprehensive?.find(
        (item) => item.check === 1
      );
      return selectedResult ? selectedResult.measure || "暂无建议" : "暂无数据";
    },
    getComprehensiveDescribe() {
      const selectedResult = this.reportData.comprehensive?.find(
        (item) => item.check === 1
      );
      return selectedResult
        ? selectedResult.describe || "暂无描述"
        : "暂无数据";
    },
    getComprehensiveDescribeName() {
      const selectedResult = this.reportData.comprehensive?.find(
        (item) => item.check === 1
      );
      return selectedResult ? selectedResult.name || "暂无描述" : "暂无数据";
    },
    getActiveTagType(level) {
      if (!level) return "";

      // 根据积极指标级别返回对应的tag类型
      switch (level) {
        case "很低":
        case "极低":
          return "danger";
        case "较低":
          return "warning";
        case "较高":
          return "success";
        case "很高":
        case "极高":
          return "primary";
        default:
          return "info";
      }
    },

    getNegativeTagType(level) {
      if (!level) return "";

      // 根据消极指标级别返回对应的tag类型
      switch (level) {
        case "正常":
          return "success";
        case "轻度":
          return "warning";
        case "中度":
          return "danger";
        case "重度":
          return "danger";
        default:
          return "info";
      }
    },

    getLevelValue(level) {
      if (!level) return 0;

      // 将文本级别转换为数字值
      switch (level.toLowerCase()) {
        case "很低":
        case "极低":
          return 1;
        case "较低":
        case "低":
          return 2;
        case "一般":
        case "较高":
        case "中等":
          return 3;
        case "很高":
        case "高":
          return 4;
        case "极高":
          return 5;
        default:
          return 3; // 默认为中等
      }
    },
    // 根据级别返回负面水平条的值
    getNegativeLevelValue(level) {
      if (!level) return 0;

      // 将文本级别转换为数字值
      switch (level.toLowerCase()) {
        case "正常":
          return 0;
        case "轻度":
          return 1;
        case "中度":
          return 2;
        case "重度":
          return 3;
        default:
          return 0; // 默认为无
      }
    },
    getActiveSegmentIndex(level) {
      if (!level) return 0;

      // 将文本级别转换为数字值
      switch (level.toLowerCase()) {
        case "很低":
        case "极低":
          return 0;
        case "较低":
        case "低":
          return 1;
        case "一般":
        case "较高":
        case "中等":
          return 2;
        case "很高":
        case "高":
          return 3;
        default:
          return 0; // 默认为很低
      }
    },
    getNegativeSegmentIndex(level) {
      if (!level) return 0;

      // 将文本级别转换为数字值
      switch (level.toLowerCase()) {
        case "正常":
          return 0;
        case "轻度":
          return 1;
        case "中度":
          return 2;
        case "重度":
          return 3;
        default:
          return 0; // 默认为正常
      }
    },
    // 添加新方法计算指示器位置
    getActiveIndicatorPosition(level) {
      const levels = ["很低", "较低", "较高", "很高"];
      const index = levels.indexOf(level);
      return index === -1 ? "0%" : `${(index + 0.5) * 25}%`;
    },

    getNegativeIndicatorPosition(level) {
      const levels = ["正常", "轻度", "中度", "重度"];
      const index = levels.indexOf(level);
      return index === -1 ? "0%" : `${(index + 0.5) * 25}%`;
    },

    formatDuration(durationStr) {
      if (!durationStr) {
        return "暂无数据";
      }

      // 移除"秒"并转换为数字
      const seconds = parseInt(durationStr.replace("秒", ""), 10);

      if (isNaN(seconds)) {
        return durationStr;
      }

      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      const remainingSeconds = seconds % 60;

      let result = "";
      if (hours > 0) {
        result += `${hours}小时`;
      }
      if (minutes > 0) {
        result += `${minutes}分钟`;
      }
      if (remainingSeconds > 0) {
        result += `${remainingSeconds}秒`;
      }

      return result || "0秒";
    },
    
    // 处理特殊视觉元素，确保Word兼容性
    async processSpecialElements(element) {
      console.log('开始处理学生报告特殊元素...');
      
      // 1. 处理学生基本信息区域
      const infoSections = element.querySelectorAll('.info-section');
      console.log(`找到 ${infoSections.length} 个学生信息区域`);
      
      infoSections.forEach((section, sectionIndex) => {
        console.log(`处理第 ${sectionIndex + 1} 个信息区域`);
        
        const infoContent = section.querySelector('.info-content');
        if (!infoContent) {
          console.log('  未找到info-content，跳过处理');
          return;
        }
        
        const infoRows = infoContent.querySelectorAll('.info-row');
        console.log(`  找到 ${infoRows.length} 个信息行`);
        
        if (infoRows.length === 0) return;
        
        // 创建表格来替代flex布局
        const table = document.createElement('table');
        table.style.cssText = `
          width: 100% !important;
          border-collapse: collapse !important;
          margin: 10px 0 !important;
          table-layout: fixed !important;
        `;
        
        infoRows.forEach((row, rowIndex) => {
          const infoItems = row.querySelectorAll('.info-item');
          console.log(`    行 ${rowIndex + 1} 中找到 ${infoItems.length} 个信息项`);
          
          const tr = document.createElement('tr');
          
          infoItems.forEach((item, itemIndex) => {
            const label = item.querySelector('label');
            const span = item.querySelector('span');
            
            const labelText = label ? label.textContent || '' : '';
            const spanText = span ? span.textContent || '' : '';
            
            console.log(`      信息项 ${itemIndex + 1}: ${labelText} ${spanText}`);
            
            const td = document.createElement('td');
            td.innerHTML = `<strong>${labelText}</strong>${spanText}`;
            td.style.cssText = `
              width: ${100/infoItems.length}% !important;
              padding: 8px 12px !important;
              border: 1px solid #e9ecef !important;
              font-size: 14px !important;
              color: #333 !important;
              background-color: white !important;
              vertical-align: middle !important;
            `;
            
            tr.appendChild(td);
          });
          
          table.appendChild(tr);
        });
        
        // 替换原始的info-content
        infoContent.parentNode.replaceChild(table, infoContent);
      });
      
      // 2. 处理所有的result-visual区域 - 转换为base64图片
      const resultVisuals = element.querySelectorAll('.result-visual');
      console.log(`找到 ${resultVisuals.length} 个result-visual区域`);
      
      for (let i = 0; i < resultVisuals.length; i++) {
        const visual = resultVisuals[i];
        console.log(`处理第 ${i + 1} 个result-visual区域`);
        
        try {
          // 使用DOM转图片的方法，完整捕获DOM元素（包括指示器）
          const canvas = await this.domToCanvas(visual);
          
          if (canvas) {
            // 转换为base64图片
            const imageData = canvas.toDataURL('image/png', 1.0);
            
            // 创建图片元素替代原始的result-visual
            const imgElement = document.createElement('img');
            imgElement.src = imageData;
            imgElement.style.cssText = `
              width: 100% !important;
              max-width: 400px !important;
              height: auto !important;
              margin: 20px 0 !important;
              display: block !important;
              border: 1px solid #ddd !important;
              border-radius: 4px !important;
            `;
            
            // 替换原始元素
            visual.parentNode.replaceChild(imgElement, visual);
            console.log(`  第 ${i + 1} 个result-visual已转换为图片（包括指示器）`);
          } else {
            // 如果DOM转图片失败，使用手动绘制的方法
            console.log(`  DOM转图片失败，使用手动绘制方法`);
            await this.manualDrawToCanvas(visual, i);
          }
          
        } catch (error) {
          console.error(`处理第 ${i + 1} 个result-visual时出错:`, error);
          // 如果图片转换失败，使用表格替代方案
          this.createFallbackTable(visual);
        }
      }
      
      console.log('学生报告特殊元素处理完成');
    },
    
    // DOM转换为画布的方法（使用原生Canvas API）
    async domToCanvas(element) {
      try {
        // 获取元素尺寸和样式
        const rect = element.getBoundingClientRect();
        const computedStyle = window.getComputedStyle(element);
        
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        
        // 设置高分辨率
        const scale = 1.5;
        canvas.width = (rect.width || 400) * scale;
        canvas.height = (rect.height || 100) * scale;
        
        ctx.scale(scale, scale);
        
        // 设置背景颜色
        ctx.fillStyle = computedStyle.backgroundColor || '#ffffff';
        ctx.fillRect(0, 0, rect.width || 400, rect.height || 100);
        
        // 手动绘制元素内容
        await this.drawElementToCanvas(ctx, element, 0, 0, rect.width || 400, rect.height || 100);
        
        return canvas;
      } catch (error) {
        console.error('DOM转换为画布失败:', error);
        return null;
      }
    },
    
    // 绘制元素到画布
    async drawElementToCanvas(ctx, element, x, y, width, height) {
      // 获取所有子元素
      const scaleElement = element.querySelector('.scale');
      const indicatorContainer = element.querySelector('.indicator-container');
      const indicator = element.querySelector('.indicator');
      
      if (scaleElement) {
        // 绘制等级条
        const scaleItems = scaleElement.querySelectorAll('.scale-item');
        await this.drawScaleBarToCanvas(ctx, scaleItems, x, y + 30, width, 50);
      }
      
      if (indicator && indicatorContainer) {
        // 绘制指示器
        const indicatorStyle = window.getComputedStyle(indicator);
        const leftPosition = indicatorStyle.left;
        
        if (leftPosition && leftPosition !== 'auto') {
          const leftPercentage = parseFloat(leftPosition.replace('%', ''));
          const indicatorX = x + (width * leftPercentage / 100);
          const indicatorY = y + 10;
          
          // 绘制三角形指示器
          ctx.fillStyle = '#FF4500';
          ctx.beginPath();
          ctx.moveTo(indicatorX, indicatorY);
          ctx.lineTo(indicatorX - 8, indicatorY - 15);
          ctx.lineTo(indicatorX + 8, indicatorY - 15);
          ctx.closePath();
          ctx.fill();
        }
      }
    },
    
    // 绘制等级条到画布
    async drawScaleBarToCanvas(ctx, scaleItems, x, y, width, height) {
      const itemWidth = width / scaleItems.length;
      
      // 根据不同的等级数量设置不同的颜色
      const colors = scaleItems.length === 4 ? 
        ['#67c23a', '#ffc107', '#ff9800', '#f56c6c'] : 
        ['#f56c6c', '#ff9800', '#67c23a', '#409eff'];
      
      scaleItems.forEach((scaleItem, index) => {
        const itemText = scaleItem.textContent || scaleItem.innerText || '';
        const isActive = scaleItem.classList.contains('active');
        const itemX = x + index * itemWidth;
        
        // 绘制等级条背景
        ctx.fillStyle = colors[index] || '#cccccc';
        ctx.fillRect(itemX, y, itemWidth, height);
        
        // 绘制边框
        ctx.strokeStyle = '#333333';
        ctx.lineWidth = 1;
        ctx.strokeRect(itemX, y, itemWidth, height);
        
        // 绘制文本
        ctx.fillStyle = '#ffffff';
        ctx.font = isActive ? 'bold 14px Microsoft YaHei' : '12px Microsoft YaHei';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        
        const textX = itemX + itemWidth / 2;
        const textY = y + height / 2;
        
        if (isActive) {
          ctx.fillText(`${itemText} ★`, textX, textY);
        } else {
          ctx.fillText(itemText, textX, textY);
        }
      });
    },
    
    // 手动绘制方法（备用方案）
    async manualDrawToCanvas(visual, index) {
      try {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        
        const rect = visual.getBoundingClientRect();
        const scale = 2;
        canvas.width = (rect.width || 400) * scale;
        canvas.height = (rect.height || 100) * scale;
        
        ctx.scale(scale, scale);
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(0, 0, canvas.width / scale, canvas.height / scale);
        
        const scaleElement = visual.querySelector('.scale');
        if (scaleElement) {
          const scaleItems = scaleElement.querySelectorAll('.scale-item');
          await this.drawScaleToCanvas(ctx, scaleItems, canvas.width / scale, canvas.height / scale);
          
          // 转换为base64图片
          const imageData = canvas.toDataURL('image/png', 1.0);
          
          const imgElement = document.createElement('img');
          imgElement.src = imageData;
          imgElement.style.cssText = `
            width: 100% !important;
            max-width: 400px !important;
            height: auto !important;
            margin: 20px 0 !important;
            display: block !important;
            border: 1px solid #ddd !important;
            border-radius: 4px !important;
          `;
          
          visual.parentNode.replaceChild(imgElement, visual);
          console.log(`  第 ${index + 1} 个result-visual已通过手动绘制转换为图片`);
        } else {
          this.createFallbackTable(visual);
        }
      } catch (error) {
        console.error('手动绘制失败:', error);
        this.createFallbackTable(visual);
      }
    },
    
    // 绘制等级条到画布
    async drawScaleToCanvas(ctx, scaleItems, width, height) {
      const itemWidth = width / scaleItems.length;
      const barHeight = height * 0.6; // 等级条高度
      const barY = height * 0.2; // 等级条Y位置
      
      // 根据不同的等级数量设置不同的颜色
      const colors = scaleItems.length === 4 ? 
        ['#67c23a', '#ffc107', '#ff9800', '#f56c6c'] : // 4个等级：正常、轻度、中度、重度
        ['#f56c6c', '#ff9800', '#67c23a', '#409eff']; // 4个等级：很低、较低、较高、很高
      
      let activeIndex = -1;
      
      // 绘制等级条和文本
      scaleItems.forEach((scaleItem, index) => {
        const itemText = scaleItem.textContent || scaleItem.innerText || '';
        const isActive = scaleItem.classList.contains('active');
        const x = index * itemWidth;
        
        if (isActive) {
          activeIndex = index;
        }
        
        // 绘制等级条背景
        ctx.fillStyle = colors[index] || '#cccccc';
        ctx.fillRect(x, barY, itemWidth, barHeight);
        
        // 绘制边框
        ctx.strokeStyle = '#333333';
        ctx.lineWidth = 2;
        ctx.strokeRect(x, barY, itemWidth, barHeight);
        
        // 绘制文本
        ctx.fillStyle = '#ffffff';
        ctx.font = isActive ? 'bold 14px Arial' : '12px Arial';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        
        const textX = x + itemWidth / 2;
        const textY = barY + barHeight / 2;
        
        if (isActive) {
          ctx.fillText(`${itemText} ★`, textX, textY);
        } else {
          ctx.fillText(itemText, textX, textY);
        }
      });
      
      // 绘制指示器（三角形）
      if (activeIndex >= 0) {
        const indicatorX = (activeIndex + 0.5) * itemWidth;
        const indicatorY = barY - 20;
        const size = 8;
        
        ctx.fillStyle = '#FF4500';
        ctx.beginPath();
        ctx.moveTo(indicatorX, indicatorY);
        ctx.lineTo(indicatorX - size, indicatorY - size * 1.5);
        ctx.lineTo(indicatorX + size, indicatorY - size * 1.5);
        ctx.closePath();
        ctx.fill();
      }
      
      // 添加说明文本
      ctx.fillStyle = '#666666';
      ctx.font = '12px Arial';
      ctx.textAlign = 'center';
      ctx.fillText('★ 表示当前测评结果等级', width / 2, height - 10);
    },
    
    // 创建替代表格（当图片转换失败时使用）
    createFallbackTable(visual) {
      const scaleElement = visual.querySelector('.scale');
      if (!scaleElement) return;
      
      const scaleItems = scaleElement.querySelectorAll('.scale-item');
      if (scaleItems.length === 0) return;
      
      // 创建表格来替代复杂的视觉效果
      const table = document.createElement('table');
      table.style.cssText = `
        width: 100% !important;
        border-collapse: collapse !important;
        margin: 20px 0 !important;
        table-layout: fixed !important;
      `;
      
      const tr = document.createElement('tr');
      
      // 根据不同的等级数量设置不同的颜色
      const colors = scaleItems.length === 4 ? 
        ['#67c23a', '#ffc107', '#ff9800', '#f56c6c'] :
        ['#f56c6c', '#ff9800', '#67c23a', '#409eff'];
      
      scaleItems.forEach((scaleItem, itemIndex) => {
        const itemText = scaleItem.textContent || scaleItem.innerText || '';
        const isActive = scaleItem.classList.contains('active');
        
        const td = document.createElement('td');
        td.textContent = itemText;
        td.style.cssText = `
          width: ${100/scaleItems.length}% !important;
          padding: 12px 8px !important;
          text-align: center !important;
          font-weight: ${isActive ? 'bold' : 'normal'} !important;
          font-size: 14px !important;
          border: 2px solid #333 !important;
          color: white !important;
          background-color: ${colors[itemIndex] || '#cccccc'} !important;
        `;
        
        if (isActive) {
          td.style.fontSize = '16px !important';
          td.style.fontWeight = 'bold !important';
          td.innerHTML = `${itemText} ★`;
        }
        
        tr.appendChild(td);
      });
      
      table.appendChild(tr);
      
      // 添加说明行
      const explanationTr = document.createElement('tr');
      const explanationTd = document.createElement('td');
      explanationTd.colSpan = scaleItems.length;
      explanationTd.textContent = '★ 表示当前测评结果等级';
      explanationTd.style.cssText = `
        padding: 8px !important;
        text-align: center !important;
        font-size: 12px !important;
        color: #666 !important;
        background-color: #f5f5f5 !important;
        border: 1px solid #333 !important;
      `;
      explanationTr.appendChild(explanationTd);
      table.appendChild(explanationTr);
      
      // 替换原始的复杂结构
      visual.parentNode.replaceChild(table, visual);
    },
    async downloadWord() {
      try {
        this.$message({
          message: "正在生成Word，请稍候...",
          type: "info",
          duration: 0,
        });

        // 需要导出的页面区域
        const exportEl =
          this.$refs.exportArea || document.querySelector(".report-container");
        if (!exportEl) {
          this.$message.closeAll();
          this.$message.error("未找到可导出的内容区域");
          return;
        }

        // 完整的Word样式，确保与页面样式一致
        const styles = `
          <style>
            body {
              font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
              color: #333;
              line-height: 1.6;
              margin: 0;
              padding: 20px;
            }
            
            .report-container {
              width: 100%;
              max-width: 1000px;
              margin: 0 auto;
              background-color: #ffffff;
              border-radius: 12px;
              overflow: hidden;
              box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            }
            
            .report-header {
              display: flex;
              align-items: center;
              padding: 25px;
              background: linear-gradient(135deg, #4a90e2, #50c878);
              color: white;
              border-radius: 12px 12px 0 0;
            }
            
            .logo-container {
              width: 80px;
              height: 80px;
              margin-right: 25px;
              border-radius: 50%;
              background-color: rgba(255,255,255,0.2);
              display: flex;
              align-items: center;
              justify-content: center;
            }
            
            .logo {
              max-width: 60%;
              max-height: 60%;
            }
            
            .title-container {
              flex-grow: 1;
            }
            
            .main-title {
              font-size: 24px;
              margin-bottom: 10px;
              font-weight: 600;
              letter-spacing: 1px;
              color: white;
            }
            
            .sub-title {
              font-size: 15px;
              opacity: 0.8;
              color: white;
            }
            
            .action-buttons {
              display: none; /* 隐藏按钮 */
            }
            
            .section-title {
              padding: 15px 25px;
              background-color: #f8f9fa;
              border-bottom: 1px solid #e9ecef;
              font-weight: 600;
              color: #2c3e50;
              display: flex;
              align-items: center;
              position: relative;
              margin: 0;
            }
            
            .section-title::before {
              content: "";
              position: absolute;
              left: 0;
              top: 50%;
              transform: translateY(-50%);
              width: 4px;
              height: 18px;
              background: linear-gradient(135deg, #4a90e2, #50c878);
              border-radius: 0 2px 2px 0;
            }
            
            /* 学生基本信息样式 - 支持新的表格结构 */
            .info-section {
              background-color: white;
              margin-bottom: 20px;
              border-radius: 8px;
              overflow: hidden;
              box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
            }
            
            /* 新的表格样式 - Word兼容 */
            .info-section table {
              width: 100% !important;
              border-collapse: collapse !important;
              margin: 10px 0 !important;
              table-layout: fixed !important;
            }
            
            .info-section td {
              padding: 8px 12px !important;
              border: 1px solid #e9ecef !important;
              font-size: 14px !important;
              color: #333 !important;
              background-color: white !important;
              vertical-align: middle !important;
            }
            
            /* 原有样式保留以防兼容性问题，但隐藏显示 */
            .info-content {
              display: none !important; /* 隐藏原有的复杂布局 */
            }
            
            .info-row {
              display: none !important;
            }
            
            /* 综合测评报告样式 */
            .result-section {
              background-color: white;
              margin-bottom: 20px;
              border-radius: 8px;
              overflow: hidden;
              box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
            }
            
            .result-content {
              padding: 20px;
            }
            
            .result-summary {
              display: flex;
              align-items: center;
              margin-bottom: 20px;
            }
            
            .result-label {
              margin-right: 10px;
              color: #606266;
              font-weight: 500;
            }
            
            .result-value {
              font-size: 18px;
              color: #409EFF;
              font-weight: bold;
            }
            
            /* result-visual 关键样式修复 - 支持图片和表格结构 */
            .result-visual {
              position: relative;
              margin-bottom: 30px;
              width: 100%;
              display: block;
            }
            
            /* 图片样式 - Word兼容 */
            .result-visual img {
              width: 100% !important;
              max-width: 400px !important;
              height: auto !important;
              margin: 20px 0 !important;
              display: block !important;
              border: 1px solid #ddd !important;
              border-radius: 4px !important;
            }
            
            /* 新的表格样式 - Word兼容 */
            .result-visual table {
              width: 100% !important;
              border-collapse: collapse !important;
              margin: 20px 0 !important;
              table-layout: fixed !important;
            }
            
            .result-visual td {
              padding: 12px 8px !important;
              text-align: center !important;
              font-size: 14px !important;
              border: 2px solid #333 !important;
              color: white !important;
            }
            
            /* 原有复杂样式保留以防兼容性问题 */
            .indicator-container {
              display: none !important; /* 隐藏原有的复杂指示器 */
            }
            
            /* 原有复杂样式保留以防兼容性问题，但隐藏显示 */
            .indicator {
              display: none !important;
            }
            
            .scale {
              display: none !important;
            }
            
            /* 表格样式 */
            .indicators-section {
              background-color: white;
              margin-bottom: 20px;
              border-radius: 8px;
              overflow: hidden;
              box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
            }
            
            .indicators-table {
              padding: 20px;
            }
            
            table {
              width: 100%;
              border-collapse: separate;
              border-spacing: 0;
              margin: 10px 0;
            }
            
            th, td {
              border: 1px solid #ebeef5;
              text-align: center;
              padding: 15px;
              border-bottom: 1px solid #f1f3f5;
            }
            
            th {
              background-color: #f8f9fa;
              font-weight: 600;
              color: #495057;
            }
            
            .indicators-result {
              padding: 20px;
            }
            
            .indicator-result-item {
              margin-bottom: 30px;
              page-break-inside: avoid;
            }
            
            .indicator-name {
              font-weight: bold;
              margin-bottom: 10px;
              color: #303133;
            }
            
            .indicator-description {
              padding: 15px 20px;
              background-color: #f9fafb;
              line-height: 1.8;
              color: #606266;
              border-top: 1px solid #e9ecef;
              font-size: 14px;
              border-radius: 0 0 8px 8px;
              margin-top: 10px;
            }
            
            .explanation-section,
            .recommendation-section {
              background-color: white;
              margin: 20px 0;
              border-radius: 8px;
              overflow: hidden;
              page-break-inside: avoid;
              box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
            }
            
            .explanation-content,
            .recommendation-content {
              padding: 25px;
              line-height: 2;
              background-color: #f9fafb;
            }
            
            .explanation-content p,
            .recommendation-content p {
              margin: 15px 0;
              color: #2c3e50;
              font-size: 14px;
            }
            
            .el-icon-check {
              color: #409eff;
              font-size: 20px;
            }
            
            .el-icon-check::before {
              content: "✓";
              font-weight: bold;
            }
            
            .report-footer {
              padding: 20px;
              text-align: right;
              background-color: #f5f7fa;
              border-top: 1px solid #e4e7ed;
            }
            
            /* 分页控制 */
            .info-section,
            .result-section,
            .indicators-section {
              page-break-inside: avoid;
              margin-bottom: 20px;
            }
            
            /* 确保颜色正确显示 */
            [style*="color: #409EFF"] {
              color: #409EFF !important;
            }
            [style*="color: #67C23A"] {
              color: #67C23A !important;
            }
            [style*="color: #E6A23C"] {
              color: #E6A23C !important;
            }
            [style*="color: #F56C6C"] {
              color: #F56C6C !important;
            }
            
            /* 强制显示样式 */
            * {
              box-sizing: border-box;
            }
            
            .result-visual * {
              display: block !important;
              visibility: visible !important;
            }
            
            .scale * {
              display: flex !important;
              visibility: visible !important;
            }
          </style>
        `;

        // 克隆元素并处理特殊内容
        const clonedEl = exportEl.cloneNode(true);
        
        console.log('开始处理Word导出特殊元素...');
        
        // 首先处理复杂的视觉元素，转换为Word兼容的表格结构或图片
        await this.processSpecialElements(clonedEl);

        // 移除不需要的元素
        const actionButtons = clonedEl.querySelector(".action-buttons");
        if (actionButtons) {
          actionButtons.remove();
        }

        // 处理图标
        const checkIcons = clonedEl.querySelectorAll(".el-icon-check");
        checkIcons.forEach((icon) => {
          icon.innerHTML = "✓";
          icon.style.color = "#409eff";
          icon.style.fontWeight = "bold";
        });

        // 确保内联样式得到保留并强化
        const styledElements = clonedEl.querySelectorAll("[style]");
        styledElements.forEach((el) => {
          const style = el.getAttribute("style");
          el.setAttribute("style", style);
        });

        // 组装完整 HTML
        const fullHtml = `
          <!DOCTYPE html>
          <html>
            <head>
              <meta charset="utf-8" />
              ${styles}
            </head>
            <body>${clonedEl.innerHTML}</body>
          </html>`;

        // 动态加载并导出
        const [{ default: HTMLDocx }, { saveAs }] = await Promise.all([
          import("html-docx-js/dist/html-docx"),
          import("file-saver"),
        ]);

        const blob = HTMLDocx.asBlob(fullHtml);
        const filename = `心理健康评估报告_${
          this.userInfo.name || "学生"
        }_${new Date().getTime()}.docx`;
        saveAs(blob, filename);

        this.$message.closeAll();
        this.$message({
          message: "Word导出成功",
          type: "success",
          duration: 2000,
        });
      } catch (err) {
        console.error("Word导出失败", err);
        this.$message.closeAll();
        this.$message.error("Word导出失败，请重试");
      }
    },
    getLevelColor(level, type) {
      // 积极指标颜色映射
      if (type === "active") {
        switch (level) {
          case "很高":
            return "#409EFF";
          case "较高":
            return "#67C23A";
          case "较低":
            return "#E6A23C";
          case "很低":
            return "#F56C6C";
          default:
            return "";
        }
      }

      // 消极指标颜色映射
      if (type === "negative") {
        switch (level) {
          case "正常":
            return "#67C23A";
          case "轻度":
            return "#E6A23C";
          case "中度":
            return "#F56C6C";
          case "重度":
            return "#F56C6C";
          default:
            return "";
        }
      }

      return "";
    },
  },
};
</script>

<style scoped>
.report-container {
  width: 90%;
  max-width: 1000px;
  margin: 30px auto;
  background-color: #ffffff;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  overflow: hidden;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
  color: #333;
}

.report-header {
  display: flex;
  align-items: center;
  padding: 25px;
  background: linear-gradient(135deg, #4a90e2, #50c878);
  color: white;
}

.logo-container {
  width: 80px;
  height: 80px;
  margin-right: 25px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo {
  max-width: 60%;
  max-height: 60%;
}

.title-container {
  flex-grow: 1;
}

.main-title {
  font-size: 24px;
  margin-bottom: 10px;
  font-weight: 600;
  letter-spacing: 1px;
}

.sub-title {
  font-size: 15px;
  opacity: 0.8;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.section-title {
  padding: 15px 25px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  font-weight: 600;
  color: #2c3e50;
  display: flex;
  align-items: center;
  position: relative;
}

.section-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background: linear-gradient(135deg, #4a90e2, #50c878);
  border-radius: 0 2px 2px 0;
}

.info-content,
.result-content,
.indicators-table,
.explanation-content,
.recommendation-content {
  padding: 20px;
}

.info-row {
  display: flex;
  margin-bottom: 15px;
}

.info-item {
  flex: 1;
  padding: 0 10px;
}

.info-item label {
  color: #606266;
  margin-right: 10px;
  font-weight: 500;
}

.info-item span {
  color: #303133;
}

.result-summary {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.result-label {
  margin-right: 10px;
  color: #606266;
}

.result-value {
  font-size: 18px;
  color: #409eff;
  font-weight: bold;
}

.result-visual {
  position: relative;
  margin-bottom: 30px;
}

.scale {
  height: 50px; /* 从40px增加到50px */
  background: linear-gradient(to right, #67c23a, #e6a23c, #f56c6c);
  border-radius: 25px;
  position: relative;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.scale-item {
  color: white;
  line-height: 50px; /* 与高度匹配 */
  font-size: 14px; /* 稍微增大字体 */
}

.scale-item.active {
  font-weight: bold;
}

.indicator-container {
  position: relative;
  height: 30px;
}

.indicator {
  position: absolute;
  top: 0;
  width: 0;
  height: 0;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-top: 20px solid #ff4500;
  transform: translateX(-50%);
  z-index: 10;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  border: 1px solid #e4e7ed;
  padding: 12px;
  text-align: center;
}

th {
  background-color: #f5f7fa;
  color: #606266;
}

.report-footer {
  padding: 20px;
  text-align: right;
  background-color: #f5f7fa;
  border-top: 1px solid #e4e7ed;
}

@media (max-width: 768px) {
  .report-container {
    width: 95%;
    margin: 15px auto;
  }

  .report-header {
    flex-direction: column;
    text-align: center;
    padding: 20px;
  }

  .logo-container {
    margin: 0 0 15px 0;
  }

  .main-title {
    font-size: 20px;
  }

  .section-title {
    padding: 12px 20px;
  }
}

.el-icon-check {
  color: #409eff;
  font-size: 20px;
  animation: fadeIn 0.5s ease;
}

@keyframes fadeIn {
  0% {
    opacity: 0;
    transform: scale(0.8);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

.indicators-table table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
}

.indicators-table th,
.indicators-table td {
  border: 1px solid #ebeef5;
  text-align: center;
  padding: 15px;
  border-bottom: 1px solid #f1f3f5;
  transition: background-color 0.3s ease;
}

.indicators-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #495057;
}

.indicators-table tr:hover {
  background-color: #f1f3f5;
}

.indicators-result {
  padding: 20px;
}

.indicator-result-item {
  margin-bottom: 30px;
}

.indicator-name {
  font-weight: bold;
  margin-bottom: 10px;
  color: #303133;
}

.indicator-container {
  position: relative;
}

.indicator-description {
  padding: 15px 20px;
  background-color: #f9fafb;
  line-height: 1.8;
  color: #606266;
  border-top: 1px solid #e9ecef;
  font-size: 14px;
  border-radius: 0 0 8px 8px;
  position: relative;
  transition: background-color 0.3s ease;
}

.indicator-description:hover {
  background-color: #f5f7fa;
}

.scale {
  display: flex;
  background: linear-gradient(to right, #67c23a, #e6a23c, #f56c6c);
  height: 40px;
  border-radius: 5px;
  position: relative;
  overflow: hidden;
}

.scale-item {
  flex: 1;
  text-align: center;
  color: #fff;
  position: relative;
  font-size: 12px;
  line-height: 40px;
  border-right: 1px solid rgba(255, 255, 255, 0.5);
  transition: background-color 0.3s ease;
}

.scale-item:last-child {
  border-right: none;
}

.scale-item.active {
  background-color: rgba(0, 0, 0, 0.2);
  font-weight: bold;
}

.indicator-container {
  position: relative;
  height: 30px;
}

.indicator {
  position: absolute;
  top: 0;
  width: 0;
  height: 0;
  border-left: 15px solid transparent;
  border-right: 15px solid transparent;
  border-top: 25px solid #ff4500;
  transform: translateX(-50%);
  z-index: 10;
}

/* 积极指标和消极指标的比例尺 */
.negative-scale {
  background: linear-gradient(to right, #67c23a, #e6a23c, #f56c6c);
}

.explanation-section,
.recommendation-section {
  background-color: white;
  margin: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: all 0.3s ease;
}

.explanation-section:hover,
.recommendation-section:hover {
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
  transform: translateY(-5px);
}

.explanation-content,
.recommendation-content {
  padding: 25px;
  line-height: 2;
  background-color: #f9fafb;
}

.explanation-content p,
.recommendation-content p {
  margin: 15px 0;
  color: #2c3e50;
  font-size: 14px;
}

/* 优化按钮与标题观感 */
.report-header {
  background: linear-gradient(120deg, #4a90e2 0%, #50c878 100%);
}
.action-buttons :deep(.el-button) {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border-radius: 6px;
}
.action-buttons :deep(.el-button--primary) {
  background-image: linear-gradient(120deg, #4a90e2, #3b82f6);
  border: none;
}
.action-buttons :deep(.el-button--success) {
  background-image: linear-gradient(120deg, #34d399, #10b981);
  border: none;
}
.section-title {
  border-bottom: 1px solid #eef0f3;
  background: #f8fafc;
}
.indicators-table tr:hover {
  background-color: #f7fafc;
}
</style>